package com.project.fortuneteller.service.impl;


import com.project.fortuneteller.mappers.FriendMapper;
import com.project.fortuneteller.mappers.MessageMapper;
import com.project.fortuneteller.pojo.Message;
import com.project.fortuneteller.pojo.dto.MessageDto;
import com.project.fortuneteller.pojo.dto.MessageHistoryDto;
import com.project.fortuneteller.service.MessageService;
import com.project.fortuneteller.utils.Result;
import com.project.fortuneteller.utils.ThreeCache;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    public MessageMapper messageMapper;

    @Autowired
    public FriendMapper friendMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     *  获取聊天记录
     *      通过 发送者 和 接收者 获取聊天记录
     * @param message
     * @return
     */
    public Result getMessageHistory(Integer userId, MessageDto message){
        // 获取 与该好友的聊天记录
        // 考虑到 好友即可能是发送方 也可能是接收方
        // 同时 按时间排序 得到 聊天记录
         // 从 redis中获取 聊天记录
        List<MessageHistoryDto> list  = new ArrayList<>(8);
        RMap<Object, Object> map = redissonClient.getMap("Message");
        map.forEach( (k,v) ->{
            String key = (String) k;
            Message ee= (Message) v;
             if(Objects.equals(ee.getSenderId(),userId) || Objects.equals(ee.getReceiverId(),userId)){
                 Message e =  (Message)  v;

                 list.add(MessageHistoryDto.builder()
                        // 获取 发送者 ID
                    .senderId(e.getSenderId().toString())
                    .content(e.getContent())
                    .senderToken( Objects.equals(e.getSenderId(), userId) ?
                    ThreeCache.userMap.get(e.getSenderId()):null)
                   .receiverId(e.getReceiverId()).date(e.getCreateTime()).build());

            }
        });

       list.sort(Comparator.comparing(MessageHistoryDto::getDate));
        return Result.success(list);
    }
    /**
     * 开始聊天 将 聊天信息 写入到聊天记录中
     */
   public Result insertMessage(Message message){
       log.info("content:{} receiverId:{}", message.getContent(), message.getReceiverId());
       return Result.success(messageMapper.insertMessage(message));
   }

    /**
     *  改变消息状态为已读
     * @param userId
     * @return
     */
    public Result setNoReadMessage(Integer userId,Integer senderId){
        messageMapper.changeMessageStatus(userId,senderId);
        return Result.success(1);
    }


}
